<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class ArticleRead extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_user_article';
    protected $cacheModel = 'content.article_read';

    /**
     * 添加已读数据
     * @param int $uid
     * @param int $type 1=>星文，2=>女神动态，3=>女神专区
     * @param int $aid 内容id
     * @return bool|int|string
     * @throws \Exception
     */
    public function saveData(int $uid, int $type, int $aid)
    {
        //判断当前文章是否已读
        $userReadIds = $this->getUserArticleReadIds($uid, $type);
        if (in_array($aid, $userReadIds))
        {
            return true;
        }
        try
        {
            $insert = ['aid' => $aid, 'uid' => $uid, 'type' => $type];
            $new_id = $this->insertGetId($insert);
        }
        catch (\Exception $e)
        {
            return false;
        }
        $this->listDataAdd($uid, [$aid => $aid], $type);
        $readKey = $type === 1 ? 'read' : 'read_num';
        //维护已读数
        (new ArticleComment())->commentOrgoodAdd($type, $aid, $readKey, 1);
        return $new_id;
    }

    /**
     * 获取用户已读的id集合，用于判断是否已读
     * @param int $uid
     * @param int $type 1=>星文，2=>女神动态，3=>女神专区
     * @return array
     * @throws \Exception
     */
    public function getUserArticleReadIds(int $uid, int $type)
    {
        $aids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType($type)->ZsGetIocData('list', function () use ($uid, $type)
        {
            try
            {
                $aids = $this->table('wechat_backup_07_18_14_43_00.app_user_article')->where(['uid' => $uid, 'type' => $type])->column('aid');
                $aids = keyValue($aids);
            }
            catch (\Exception $e)
            {
                $aids = [];
            }
            return $aids;
        });

        return $aids;
    }
}
